﻿using System;
using System.Globalization;
using System.Web.Security.AntiXss;
using System.Web.UI;
using System.Web.UI.WebControls;
using InhollandAir.auxiliary;

namespace InhollandAir
{
    public partial class Account : Page
    {
        private static int _userId;
        private static Miles _miles;

        protected void Page_Load(object sender, EventArgs e)
        {
            CustomerFactory.TryLogin((customer, success) =>
                {
                    if (!success) Response.Redirect("Login.aspx");
                    else
                    {
                        lblUserName.Text = customer.Username;
                        _userId = customer.Id;
                        foreach (var li in Sql.GetAllCountriesInWorld())
                            ddlAllCountry.Items.Add(li);

                        if (!Page.IsPostBack)
                        {
                            LoadAccountDetails();
                            LoadMilesDetails();
                            LoadBookings();
                        }
                    }
                });
        }

        protected void Logout(object sender, EventArgs e)
        {
            CustomerFactory.Logout(true);
        }

        protected void LoadBookings()
        {
            try
            {
                gvBookings.DataSource = Sql.GetFullBookingOverviewByUserId(_userId);
                gvBookings.DataBind();

                for (int i = 0; i < gvBookings.Rows.Count; i++)
                    if (!ddlCancelBooking.Items.Contains(new ListItem(AntiXssEncoder.HtmlEncode(gvBookings.Rows[i].Cells[0].Text, false))))
                        ddlCancelBooking.Items.Add(new ListItem(AntiXssEncoder.HtmlEncode(gvBookings.Rows[i].Cells[0].Text, false)));

                if (ddlCancelBooking.Items.Count < 1)
                {
                    ddlCancelBooking.Visible = false;
                    btnCancelBooking.Visible = false;
                    lblCancelNote.Text = AntiXssEncoder.HtmlEncode("Your booking history is empty.", false);
                }
            }
            catch (Exception ex)
            {
                ddlCancelBooking.Visible = false;
                btnCancelBooking.Visible = false;
                lblCancelNote.Visible = false;
                Logging.LogEvent(_userId, Request.Url, "Could not show booking in account page", ex.Message, true);
            }

        }

        protected void LoadAccountDetails()
        {
            try
            {
                var details = Sql.GetPersonDetails(_userId);
                string salutation = string.Empty;

                lblFirstName.Text = AntiXssEncoder.HtmlEncode(details["firstname"], false);
                lblFamilyName.Text = AntiXssEncoder.HtmlEncode(details["familyname"], false);
                lblBirthdate.Text = AntiXssEncoder.HtmlEncode(details["birthdate"], false);
                if (string.Equals(details["sex"], "m"))
                {
                    lblSex.Text = "Male";
                    salutation = "Mr.";
                }
                else if (string.Equals(details["sex"], "f"))
                {
                    lblSex.Text = "Female";
                    salutation = "Mrs.";
                }
                txtPhoneNumber.Text = AntiXssEncoder.HtmlEncode(details["phonenumber"], false);
                txtEmailAddress.Text = AntiXssEncoder.HtmlEncode(details["emailaddress"], false);
                ddlAllCountry.SelectedValue = AntiXssEncoder.HtmlEncode(details["country"], false);
                txtPostalCode.Text = AntiXssEncoder.HtmlEncode(details["postalcode"], false);
                txtHouseNumber.Text = AntiXssEncoder.HtmlEncode(details["number"], false);

                lblInHollandMiles.Text = AntiXssEncoder.HtmlEncode(details["balance"], false);
                lblLastTransaction.Text = AntiXssEncoder.HtmlEncode(details["lasttransaction"], false);

                lblFullName.Text = AntiXssEncoder.HtmlEncode(string.Format("{0} {1}", salutation, details["familyname"]), false);
            }
            catch (Exception)
            {
                lblFirstName.Text = AntiXssEncoder.HtmlEncode("Could not find your account details!", false);
            }

        }

        protected void LoadMilesDetails()
        {
            _miles = new Miles().GetMiles(_userId);
            lblInHollandMiles.Text = AntiXssEncoder.HtmlEncode(_miles.Balance.ToString(CultureInfo.InvariantCulture), false);
            lblLastTransaction.Text = AntiXssEncoder.HtmlEncode(_miles.LastTransaction.ToString(CultureInfo.InvariantCulture), false);
        }

        protected void BtnUpdateDetailsClick(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            if (Convert.ToInt16(ddlAllCountry.SelectedValue) > ddlAllCountry.Items.Count ||
                Convert.ToInt16(ddlAllCountry.SelectedValue) <= 0)
                Response.Write(string.Format("<script>alert('Invalid country');</script>"));
            else
                Response.Write(string.Format("<script>alert('{0}');</script>",
                                             AntiXssEncoder.HtmlEncode(Sql.UpdatePersonalDetails(_userId, txtPhoneNumber.Text,
                                                                       txtEmailAddress.Text,
                                                                       ddlAllCountry.SelectedValue, txtPostalCode.Text,
                                                                       txtHouseNumber.Text), false)));
        }

        protected void BtnUpdatePasswordClick(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            Response.Write(string.Format("<script>alert('{0}');</script>", AntiXssEncoder.HtmlEncode(Sql.UpdatePasswordDetails(lblUserName.Text, txtNewPassword.Text, _userId), false)));
        }

        protected void BtnCancelBookingClick(object sender, EventArgs e)
        {
            int num;
            if (int.TryParse(ddlCancelBooking.SelectedValue, out num))
                if (Sql.CancelBookingById(ddlCancelBooking.SelectedValue, _userId, -1) == "1")
                {
                    ddlCancelBooking.Items.Remove(ddlCancelBooking.SelectedItem);
                    if (ddlCancelBooking.Items.Count < 1)
                    {
                        ddlCancelBooking.Visible = false;
                        btnCancelBooking.Visible = false;
                        lblCancelNote.Visible = false;
                    }
                    Logging.LogEvent(_userId, Request.Url, "Booking: canceled succesfull", "Booking cancelled.", false);
                    lblCancelResult.Text = AntiXssEncoder.HtmlEncode("Booking cancelled.", false);
                    LoadBookings();
                }
                else
                {
                    Logging.LogEvent(_userId, Request.Url, "Booking: could not cancel", "Could not cancel your booking, please contact our helpdesk to manually cancel your booking.", false);
                    lblCancelResult.Text =
                       AntiXssEncoder.HtmlEncode("Could not cancel your booking, please contact our helpdesk to manually cancel your booking.", false);
                }
            else
                lblCancelResult.Text =
                        AntiXssEncoder.HtmlEncode("Could not cancel your booking, your booking ID is invalid.", false);
        }
    }
}